package com.github.bitsapling.sapling.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.github.bitsapling.sapling.result.GraceJSONResult;
import com.github.bitsapling.sapling.result.ResponseStatusEnum;
import com.github.bitsapling.sapling.entity.InvitationCode;
import com.github.bitsapling.sapling.entity.User;
import com.github.bitsapling.sapling.service.InvitationService;
import com.github.bitsapling.sapling.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController    //表示可以被前端调用
@RequestMapping("invite")
@Slf4j
public class InvitationController {
    @Resource
    private UserService userService;

    @Resource
    private InvitationService invitationService;

    /**
     * 生成邀请码
     * @param count 要生成的邀请码个数
     * @return 包含生成的邀请码列表的响应结果
     */
    @PostMapping("codes")
    @SaCheckPermission(value = "user:invite", orRole = "admin")
    public GraceJSONResult generateInvitationCodes(@RequestParam(defaultValue = "1") int count) {
        // 获得当前登录用户的ID
        User user = userService.getUserById(StpUtil.getLoginIdAsLong());
        if (user == null) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.UN_LOGIN);
        }
        InvitationCode invitationDetail = new InvitationCode();
        invitationDetail.setCreateBy(user.getUsername());
        invitationDetail.setCreateTime(LocalDateTime.now());
        invitationDetail.setExpiresTime(LocalDateTime.now().plusDays(7));
        // 调用 InvitationService 生成邀请码
        List<String> invitationCodes = invitationService.generateInvitationCodes(invitationDetail,count);
        return GraceJSONResult.ok(invitationCodes);
    }

    @GetMapping("/list")
    @SaCheckPermission(value = "user:invite", orRole = "admin")
    public GraceJSONResult list() {
        return GraceJSONResult.ok(invitationService.showInvitationUnused());
    }

}


